package com.idlecode.manage;

import cn.hutool.core.collection.CollUtil;
import com.idlecode.bean.CodeFormatEntity;
import com.idlecode.bean.DataBaseEntity;
import com.idlecode.config.GenDataSource;
import com.idlecode.service.CodeFormatService;
import com.idlecode.service.DataBaseService;
import com.idlecode.statics.CodeFormat;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.JBTabbedPane;
import com.intellij.ui.table.JBTable;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.Map;

/**
 * @program: IdleCode
 * @description
 * @author: rongjuwei
 * @create: 2024-02-06 16:00
 **/
public class CodeFormatManage extends DialogWrapper {
    // 创建表格模型
    private DefaultTableModel tableModel;
    private JTable table;
    // 创建下拉框
    private final static JComboBox<String> comboBox = new JComboBox<>(CodeFormat.getCodeFormats().keySet().toArray(new String[0]));

    private List<DataBaseEntity> dataBaseList;

    private JPanel jPanel;

    private GenDataSource genDataSource;

    public CodeFormatManage(GenDataSource genDataSource) {
        super(true); // 设置为模态对话框
        setTitle("代码格式设置");
        this.genDataSource = genDataSource;
        dataBaseList = DataBaseService.getDataBaseList(genDataSource);
        init();
    }

    @Nullable
    @Override
    protected JComponent createCenterPanel() {
        jPanel = new JPanel(new BorderLayout());
        jPanel.setPreferredSize(new Dimension(650, 600));
        tableModel = new DefaultTableModel();

        // 添加列名
        tableModel.addColumn("数据库");
        tableModel.addColumn("代码格式");

        // 创建表格
        table = new JBTable(tableModel);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);

        if (CollUtil.isNotEmpty(dataBaseList)) {
            CodeFormatService instance = CodeFormatService.getInstance();
            CodeFormatEntity codeFormatEntity = instance.getCodeFormatEntity(genDataSource.getDsId());
            for (DataBaseEntity dataBaseEntity : dataBaseList) {
                String owner = dataBaseEntity.getOwner();
                // 添加数据行
                tableModel.addRow(new Object[]{owner, codeFormatEntity.infoGet(owner)});
            }
            // 设置下拉框为单元格编辑器
            table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(comboBox));
        }

        // 设置表头居中
        DefaultTableCellRenderer headerRenderer = new DefaultTableCellRenderer();
        headerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
        table.getTableHeader().setDefaultRenderer(headerRenderer);

        // 将表格放置在滚动窗格中
        JScrollPane scrollPane = new JBScrollPane(table);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        jPanel.add(scrollPane, BorderLayout.CENTER);

        return jPanel;
    }

    @Override
    protected void doOKAction() {
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        int rowCount = model.getRowCount();

        CodeFormatEntity codeFormatEntity = CodeFormatService.getInstance().getCodeFormatEntity(genDataSource.getDsId());
        for (int row = 0; row < rowCount; row++) {
            // 从模型中获取数据库名称和代码格式
            Object database = model.getValueAt(row, 0);
            Object codeFormat = model.getValueAt(row, 1);
            codeFormatEntity.infoPut(database, codeFormat);
        }
        CodeFormatService.getInstance().setCodeFormatEntity(codeFormatEntity);
        super.doOKAction();
    }


    @Override
    protected @NotNull JPanel createButtonsPanel(@NotNull List<? extends JButton> buttons) {
        JPanel buttonsPanel = super.createButtonsPanel(buttons);
        JButton helpButton = createHelpButton(new Insets(0, 0, 0, 0));
        // 将帮助按钮添加到面板的最左边
        buttonsPanel.add(helpButton, 0);
        return buttonsPanel;
    }

    @Override
    protected @NotNull JButton createHelpButton(@NotNull Insets insets) {
        // 这里可以使用默认的创建帮助按钮的实现
        JButton helpButton = super.createHelpButton(insets);
        helpButton.addActionListener(e -> doHelpAction());
        helpButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                doHelpAction();
            }
        });
        return helpButton;
    }

    @Override
    protected void doHelpAction() {
        showCodeFormatHelp(jPanel);
        super.doHelpAction();
    }

    public static void showCodeFormatHelp(JPanel jPanel) {
        // 获取顶级窗口作为对话框的父容器
        Window topLevelWindow = SwingUtilities.getWindowAncestor(jPanel);

        // 创建帮助对话框
        JDialog helpDialog = new JDialog(topLevelWindow, "帮助", Dialog.ModalityType.APPLICATION_MODAL);
        helpDialog.setSize(800, 600);
        helpDialog.setLayout(new BorderLayout());

        // 创建标签页
        JTabbedPane tabbedPane = new JBTabbedPane();

        // 设置字体
        Font defaultFont = UIManager.getFont("Label.font");
        Font font = defaultFont.deriveFont(14f); // 16f 表示字体大小为 16
        //Font font = new Font("Arial", Font.PLAIN, 16);

        Map<String, String> codeFormats = CodeFormat.getCodeFormats();
        for (Map.Entry<String, String> codeFormatEntry : codeFormats.entrySet()) {
            // 添加第一个标签页
            JTextArea textArea = new JTextArea(10, 30);
            textArea.setText(codeFormatEntry.getValue());
            //这个方法用于启用自动换行功能。设置为 true 时，如果一行文本超出 JTextArea 的宽度，文本将自动换行到下一行。
            textArea.setLineWrap(true);
            //这个方法指定换行时以单词为单位进行换行，而不是以字符为单位。设置为 true 时，换行会在单词之间进行，
            // 以保证单词不会被截断。如果设置为 false，换行会在字符之间进行，可能会截断单词。
            textArea.setWrapStyleWord(true);
            //这个方法用于设置 JTextArea 为不可编辑状态。设置为 false 时，用户无法修改文本内容，但仍然可以选择和复制文本。
            textArea.setEditable(false);
            textArea.setFont(font);
            JScrollPane scrollPane1 = new JBScrollPane(textArea);
            tabbedPane.addTab(codeFormatEntry.getKey(), scrollPane1);
        }

        helpDialog.add(tabbedPane, BorderLayout.CENTER);
        // 将对话框设置在屏幕中央
        helpDialog.setLocationRelativeTo(null);
        helpDialog.setVisible(true);
    }
}
